package com.xyun.task.job;

import io.xyun.mpapi.util.HttpTool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.json.Json;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.xyun.base.utils.ConfigUtils;
import com.xyun.base.utils.HttpUtils;
import com.xyun.base.utils.SpringContextHolder;
import com.xyun.task.service.TaskService;

/**
 * 微信绑定送积分，每天处理一次
 * @author: 	xyun
 * @version: 	1.0 
 * @Copyright:  Copyright (c) 2016 
 * @createtime: 2016年6月27日 下午1:53:56
 */
@Service
@Lazy(false)
public class WxBindScoreJob
{
	private TaskService service = SpringContextHolder.getBean(TaskService.class);
	private Log log = Logs.get();
	
	public void wxBindScore(){
		handleFail();
		
		List bindList = service.getLastBindData();
		if(null == bindList || bindList.size()<=0){
			return;
		}
		for(Object obj:bindList){
			Map data = (Map)obj;
			String custno = (String)data.get("CUSTNO");
			String custno_crm = (String)data.get("CUSTNO_CRM");
			String certno = (String)data.get("CER_NO");
			String mpid = (String)data.get("WEIXIN_PK");
			String openid = (String)data.get("OPENID");
			boolean iscertNo = certno.length()==18?true:false;
			boolean isnew = service.isNewBind(custno,custno_crm);
			if(!isnew){
				continue;
			}
			if(iscertNo){
				addScore("0",certno,custno,custno_crm,mpid,openid,"0");
			}else{
				try {
					//调用金证接口，根据客户号查询用户的归属
					boolean iszx= custno==null?false:true;
					log.info(iszx);
					String funcNo = iszx?"100514":"100515";
					String rqSource = "wxtask";
					String wxweb_url=ConfigUtils.get("wxweb_url");
					wxweb_url = String.format(wxweb_url,funcNo,rqSource)+"&custno="+custno+"&custno_crm="+custno_crm;
					String resultJson = HttpTool.get(wxweb_url);
					Map resultMap = Json.fromJson(Map.class,resultJson);
					log.info("====="+resultMap.toString());
					boolean success = (boolean)resultMap.get("success");
					if(success){
						//Map temp = (Map)Json.fromJson((String)resultMap.get("results"));
						Object objtmp = resultMap.get("results");
						Map temp = Json.fromJson(Map.class,Json.toJson(objtmp));
						Map dataset =Json.fromJson(Map.class,Json.toJson(temp.get("DataSet")));
						String certType = (String)dataset.get("certificatetype");
						String certNo = (String)dataset.get("certificateno");
						addScore(certType,certNo,custno,custno_crm,mpid,openid,"0");
					}else{
						log.error("新增积分失败，用户信息："+ data.toString()+" 错误信息："+(String)resultMap.get("errorMsg"));
						service.addScoreLog("", certno, custno, custno_crm, mpid, openid, "-1", "查询客户归属错误:"+(String)resultMap.get("errorMsg"));
					}
				} catch (Exception e) {
					log.error("新增积分失败，用户信息："+ data.toString(),e);
					service.addScoreLog("", certno, custno, custno_crm, mpid, openid, "-1", "系统错误:"+e.getMessage());
				}
				
			}
		}
	}
	public void addScore(String certType,String certNo,String custno,String custno_crm,String mpid,String openid,String result){
		if(certType == null ||certType.equals("") || certNo==null || certNo.equals("")){
			log.error("证件类型【certType】证件号码【certNo】不能为空！");
			return;
		}
		boolean isoldbind = service.isOldBind(certType, certNo);
		if(isoldbind){
			return ;
		}
		String resultStr = callAddScore(certType,certNo);
		// add log
		service.addScoreLog(certType, certNo, custno, custno_crm, mpid, openid, result, resultStr);
	}
	
	/**
	 * 处理失败的(纯直销客户，15点之前的需要T+1,15点之后的需要T+2)
	 * @author：	 xyun
	 * @createtime： 2016年7月4日 上午9:01:15
	 */
	public void handleFail(){
		log.info("处理绑定送积分失败记录开始");
		List list = service.getScoreFail();
		if(null!=list && list.size()>0){
			log.info("失败记录有"+list.size());
			for(Object obj:list){
				try {
					Map map = (Map)obj;
					String certType= (String)map.get("CERTTYPE");
					String certNo = (String)map.get("CERTNO");
					String mpid=(String)map.get("MPID");
					String resultStr = callAddScore(certType,certNo);
					service.updateScoreLog(certType, certNo, mpid, "1", resultStr);
				} catch (Exception e) {
					log.error("处理绑定送积分失败：",e);
				}
				
			}
			
		}
		
	}
	
	public String callAddScore(String certType,String certNo){
		String score="2000";//添加积分
		String code="A300";//业务代码 A100-开户送积分，A200 微信开户送积分 A300 微信绑定送积分
		Map<String, String> map = new HashMap<String, String>();
		String scoreadd_url = ConfigUtils.get("scoreadd_url");
		map.put("certType", certType);
		map.put("certNo", certNo);
		map.put("score", score);
		map.put("code", code);
		log.info("新增绑定积分开始："+map.toString());
		String resultStr = HttpUtils.post(scoreadd_url,map);
		log.info("新增绑定积分结果："+resultStr);
		return resultStr;
	}
}
